package org.bird.concurrent.lock;

import java.util.concurrent.locks.Lock;

/**
 * 可重入锁
 * @author liangjf
 *
 */
public class ReentrantLock {

	private Lock lock = new java.util.concurrent.locks.ReentrantLock();

	public static void main(String[] args) {
		final ReentrantLock test = new ReentrantLock();
		Thread tryLock = new Thread(new Runnable() {
			public void run() {
				test.tryLock();
			}
		}, "tryLock_thread");

		Thread lock = new Thread(new Runnable() {
			public void run() {
				test.lock();
			}
		}, "lock_thread");

		tryLock.start();
		lock.start();
	}

	public void tryLock() {

		long beginTime = System.currentTimeMillis();
		while (System.currentTimeMillis() - beginTime < 100) {
		}
		// 当前线程尝试获得锁，如果获得锁返回true，否则返回false
		if (lock.tryLock()) {
			try {
				System.out.println(Thread.currentThread().getName() + " tryLock get lock");
			} finally {
				lock.unlock();
				System.out.println(Thread.currentThread().getName() + " tryLock release lock");
			}
		} else {
			System.out.println(Thread.currentThread().getName() + " tryLock can not get lock");
		}

	}

	public void lock() {
		try {
			// 当前线程在锁可用时直接获得锁，锁不可用时阻塞当前线程
			lock.lock();
			System.out.println(Thread.currentThread().getName() + " lock get lock");
			long beginTime = System.currentTimeMillis();
			while (System.currentTimeMillis() - beginTime < 1000) {
			}
		} finally {
			lock.unlock();
			System.out.println(Thread.currentThread().getName() + " lock release lock");
		}

	}
}
